package dao;

import entity.Message;
import entity.MessageVo;

import java.sql.SQLException;
import java.util.List;

/**
 * 留言表操作的类
 */
public class MessageDao extends BaseDao{
    /**
     * 新增留言
     */
    public boolean addMessage(Message msg) throws SQLException {
        String sql = "insert into message (user_id,msg_content,create_time) values (?,?,?)";
        int i = executeUpdate(sql, msg.getUser_id(), msg.getMsg_content(), msg.getCreate_time());
        return i > 0;
    }

    /**
     * 查询所有留言
     */
    public List<MessageVo> getAllMsg() throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        String sql = "SELECT\n" +
                "\ta.*,\n" +
                "\tb.nickname,\n" +
                "\tb.gender\n" +
                "FROM\n" +
                "\tmessage a\n" +
                "LEFT JOIN userinfo b ON a.user_id = b.id\n" +
                "ORDER BY a.create_time DESC";

        List<MessageVo> messageList = executeQuery(MessageVo.class, sql);
        return messageList;
    }

    /**
     * 根据用户id查询留言
     */
    public List<MessageVo> getMsgByUserId(String userId) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        String sql = "SELECT\n" +
                "\ta.*,\n" +
                "\tb.nickname,\n" +
                "\tb.gender\n" +
                "FROM\n" +
                "\tmessage a\n" +
                "LEFT JOIN userinfo b ON a.user_id = b.id\n" +
                "WHERE a.user_id=?\n" +
                "ORDER BY a.create_time DESC";
        List<MessageVo> messageList = executeQuery(MessageVo.class, sql, userId);
        return messageList;
    }
}
